package com.cqs.leetcode.math;

public class CountAndSay38 {
    static class Solution {
        public String countAndSay(int n) {
            if (n <= 0) return "";
            String num = "1";
            while (--n > 0) {
                num = nextNum(num);
            }
            return num;
        }

        /**
         * 从左向右扫描
         * 记录每个数字连续出现的次数
         * 如111221 --> 111,22,1 ---> 312211（3个1 2个2 1个1）
         *
         * @param num
         * @return
         */
        private String nextNum(String num) {
            int len = -1;
            StringBuilder sb = new StringBuilder();
            char pre = num.charAt(++len);
            char c = pre;
            int cnt = 1;
            while (++len < num.length()) {
                c = num.charAt(len);
                if (c == pre) {
                    ++cnt;
                } else {
                    sb.append(cnt);
                    sb.append(pre);
                    pre = c;
                    cnt = 1;
                }
            }
            sb.append(cnt);
            sb.append(c);
            return sb.toString();
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        for (int i = 0; i <= 30; i++) {
            System.out.println(i + "\t result:" + solution.countAndSay(i));
        }
    }
}
